import { defineStore } from 'pinia'
import { ref } from 'vue'
import { api } from '@/services/api'
import { signalRService } from '@/services/signalr'

export const useChatStore = defineStore('chat', () => {
  const friends = ref([])
  const requests = ref([])
  const groups = ref([])
  const currentChat = ref(null)
  const messages = ref([])
  const users = ref([])
  const isLoading = ref(false)
  const isTyping = ref(false)
  const typingUserId = ref(null)

  const loadFriends = async () => {
    try {
      const response = await api.get('/users/friends')
      friends.value = response.data
    } catch (error) {
      console.error('Failed to load friends:', error)
    }
  }
  
  const loadFriendRequests = async () => {
    try {
      const response = await api.get('/users/friend-requests')
      requests.value = response.data
    } catch (error) {
      console.error('Failed to load friend requests:', error)
    }
  }

  const loadGroups = async () => {
    try {
      const response = await api.get('/groups')
      groups.value = response.data
    } catch (error) {
      console.error('Failed to load groups:', error)
    }
  }

  const searchUsers = async (query) => {
    try {
      const response = await api.get(`/users/search?query=${query}`)
      users.value = response.data
    } catch (error) {
      console.error('Failed to search users:', error)
    }
  }

  const addFriend = async (friendId) => {
    try {
      await api.post(`/users/friends/${friendId}`)
      await loadFriends()
      await loadFriendRequests()
      return { success: true }
    } catch (error) {
      return { 
        success: false, 
        message: error.response?.data?.message || 'Failed to add friend' 
      }
    }
  }

  const respondToRequest = async (friendshipId, accept) => {
    try {
      await api.post(`/users/friend-requests/${friendshipId}/respond`, { accept })
      // 从列表中移除
      requests.value = requests.value.filter(r => r.id !== friendshipId)
    } catch (error) {
      console.error('Failed to respond to friend request:', error)
    }
  }

  const removeFriend = async (friendId) => {
    try {
      await api.delete(`/users/friends/${friendId}`)
      await loadFriends()
      return { success: true }
    } catch (error) {
      return { 
        success: false, 
        message: error.response?.data?.message || 'Failed to remove friend' 
      }
    }
  }

  const createGroup = async (groupData) => {
    try {
      const response = await api.post('/groups', groupData)
      await loadGroups()
      return { success: true, group: response.data }
    } catch (error) {
      return { 
        success: false, 
        message: error.response?.data?.message || 'Failed to create group' 
      }
    }
  }

  const loadPrivateMessages = async (friendId, page = 1) => {
    try {
      isLoading.value = true
      const response = await api.get(`/messages/private/${friendId}?page=${page}`)
      
      if (page === 1) {
        messages.value = response.data
      } else {
        messages.value = [...response.data, ...messages.value]
      }
      
      return response.data.length
    } catch (error) {
      console.error('Failed to load messages:', error)
      return 0
    } finally {
      isLoading.value = false
    }
  }

  const loadGroupMessages = async (groupId, page = 1) => {
    try {
      isLoading.value = true
      const response = await api.get(`/messages/group/${groupId}?page=${page}`)
      
      if (page === 1) {
        messages.value = response.data
      } else {
        messages.value = [...response.data, ...messages.value]
      }
      
      return response.data.length
    } catch (error) {
      console.error('Failed to load messages:', error)
      return 0
    } finally {
      isLoading.value = false
    }
  }

  const sendPrivateMessage = async (friendId, content) => {
    try {
      await signalRService.sendPrivateMessage(friendId, content)
    } catch (error) {
      console.error('Failed to send message:', error)
    }
  }

  const sendGroupMessage = async (groupId, content) => {
    try {
      await signalRService.sendGroupMessage(groupId, content)
    } catch (error) {
      console.error('Failed to send message:', error)
    }
  }

  const markAsRead = async (messageId) => {
    try {
      await api.post(`/messages/read/${messageId}`)
    } catch (error) {
      console.error('Failed to mark message as read:', error)
    }
  }

  const markAllAsRead = async (friendId = null, groupId = null) => {
    try {
      let url = '/messages/read/all'
      if (friendId) url += `?friendId=${friendId}`
      if (groupId) url += `?groupId=${groupId}`
      
      await api.post(url)
    } catch (error) {
      console.error('Failed to mark messages as read:', error)
    }
  }

  // SignalR event handlers
  const setupSignalRHandlers = () => {
    signalRService.onReceivePrivateMessage((message) => {
      if (currentChat.value && 
          currentChat.value.type === 'private' && 
          currentChat.value.id === message.senderId) {
        messages.value.push(message)
      }
    })
    
    signalRService.onReceiveGroupMessage((message) => {
      if (currentChat.value && 
          currentChat.value.type === 'group' && 
          currentChat.value.id === message.groupId) {
        messages.value.push(message)
      }
    })
    
    signalRService.onUserTyping((userId, typing) => {
      if (currentChat.value && 
          currentChat.value.type === 'private' && 
          currentChat.value.id === userId) {
        isTyping.value = typing
        typingUserId.value = userId
      }
    })
    
    signalRService.onFriendStatusChanged((userId, status) => {
      const friend = friends.value.find(f => f.id === userId)
      if (friend) {
        friend.status = status
        if (status === 'offline') {
          friend.lastSeen = new Date()
        }
      }
    })
    
    signalRService.onMessageRead((messageId) => {
      const message = messages.value.find(m => m.id === messageId)
      if (message) {
        message.isRead = true
      }
    })
  }

  return {
    friends,
    requests,
    groups,
    currentChat,
    messages,
    users,
    isLoading,
    isTyping,
    typingUserId,
    loadFriends,
    loadFriendRequests,
    loadGroups,
    searchUsers,
    addFriend,
    respondToRequest,
    removeFriend,
    createGroup,
    loadPrivateMessages,
    loadGroupMessages,
    sendPrivateMessage,
    sendGroupMessage,
    markAsRead,
    markAllAsRead,
    setupSignalRHandlers
  }
})